<template>
  <div
    id="spreadRoot"
    class="bg-2F3843 c-flex-column"
  >
    <div class="c-br20 c-flex-center c-flex-row c-flex-grow1 c-h0 c-p">
      <div class="c-ww394 c-br20">
        <img
          id="spreadImg"
          class="c-ww394 c-br20 app-save-img"
          src=""
          alt=""
        >
      </div>
    </div>
    <footer class="c-bg-white c-hh180 c-bd-t1 c-w100 c-ph24" :class="isShowMarginBottom ? 'c-mb80' : ''">
      <p class="c-textAlign-c c-fs20 c-fc-sblack c-mt20 c-mb20">长按上方图片保存，分享给朋友</p>
      <div
        class="c-contexty-hidden c-contextX-scroll c-ws-n"
        style="overflow:auto"
        id="scroll"
      >
        <template v-for="(item,index) in promoteData">
          <div
            :key="index"
            @click="clickChangeImg(item.promotionNum)"
            v-if="item.promotionImg && item.isShow == 1"
            class="c-p c-mr20 c-inlineblack c-hh100 c-ww100"
          >
            <img
              class="c-hh100 c-ww100 c-br10 img-pe-none"
              :src="$addXossFilter(promotionImg(item))"
              alt
            >
            <img
              v-show="curPromotionNum == item.promotionNum && item.isShow == 1"
              class="c-pa c-ww32 c-hh32 check img-pe-none"
              src="../../../assets/check.png"
              alt
            >
          </div>
        </template>
      </div>
    </footer>
    <!-- 绘图 -->
    <div class="canvasContent">
      <!-- 系统图1 -->
      <template v-for="(item, index) in promoteData">
        <div
          class="anvasContent"
          :id="'canvas' + item.promotionNum"
          :key="index"
          v-if="item.promotionNum == 1 && curPromotionNum == item.promotionNum"
        >
          <img
            class="c-w100 c-h img-pe-none"
            :src="$addXossFilter(item.isCustomImg == 1 ? item.promotionImg : DEFAULT_BG_LIST[1])"
            alt=""
          >
          <article class="c-pa c-flex-row c-aligni-center c-justify-sb" style="width:100%;font-size:26px;top:913px;padding-left:30px;padding-right:30px;">
            <section style="width:390px;">
              <p
                :style="'color:'+item.wordColor"
              >{{textContentOption(item)}}</p>
              <p
                style="margin-top:30px;"
                :style="'color:'+item.wordColor"
              >{{text3ContentOption(item)}}</p>
            </section>
            <section class="c-flex-column">
              <p
                class="c-fc-gray"
                style="font-size:18px;;padding-bottom:15px;"
              >长按识别二维码</p>
              <img
                class="c-bg-white"
                style="width:127px;height:127px;"
                :src="$addXossFilter(mpQrcode)"
                alt=""
              >
            </section>
          </article>
          <p
            v-if="isShowCkjr"
            class="c-pa c-fc-sgray"
            style="font-size:20px;left:50%;bottom:12px;transform:translate(-50%, 0);"
          >{{showCkjrText}}</p>

        </div>
        <div
          class="anvasContent"
          :id="'canvas' + item.promotionNum"
          :key="index"
          v-else-if="item.promotionNum == 2 && curPromotionNum == item.promotionNum"
        >
          <img
            class="c-w100 c-h img-pe-none"
            :src="$addXossFilter(item.isCustomImg == 1 ? item.promotionImg : DEFAULT_BG_LIST[2])"
            alt=""
          >
          <p
            class="c-pa c-ws-n"
            style="font-size:28px;left:50%;top:808px;transform:translate(-50%, 0);"
            :style="'color:'+item.wordColor"
          >{{textContentOption(item)}}</p>
          <p
            class="c-pa c-ws-n"
            style="font-size:28px;left:50%;bottom:248px;transform:translate(-50%, 0);"
            :style="'color:'+item.wordColor"
          >{{text3ContentOption(item)}}</p>
          <p
            v-if="isShowCkjr"
            class="c-pa c-fc-sgray"
            style="font-size:20px;left:50%;bottom:12px;transform:translate(-50%, 0);"
          >{{showCkjrText}}</p>
          <img
            class="c-pa c-bg-white"
            style="right:246px;bottom:70px;width:148px;height:148px;"
            :src="$addXossFilter(mpQrcode)"
            alt=""
          >
        </div>
        <div
          class="anvasContent"
          :id="'canvas' + item.promotionNum"
          :key="index"
          v-else-if="item.promotionNum == 3 && curPromotionNum == item.promotionNum"
        >
          <img
            class="c-w100 c-h img-pe-none"
            :src="$addXossFilter(item.isCustomImg == 1 ? item.promotionImg : DEFAULT_BG_LIST[3])"
            alt=""
          >
          <article class="c-pa c-flex-row c-aligni-center c-justify-sb" style="font-size:26px;top:875px;width:100%;padding-left:68px;padding-right:45px;">
            <section class="c-flex-column">
              <img
                class="c-bg-white"
                style="bottom:110px;width:148px;height:148px;"
                :src="$addXossFilter(mpQrcode)"
                alt=""
              >
              <img
                class=""
                style="margin-top:14px;width:143px;height;24px;"
                :src="$addXossFilter(qr)"
                alt=""
              >
            </section>
            <section style=";width:312px;">
              <p
                class="c-textAlign-r"
                :style="'color:'+item.wordColor"
              >{{textContentOption(item)}}</p>
              <p
                class="c-textAlign-r"
                style="margin-top:30px;"
                :style="'color:'+item.wordColor"
              >{{text3ContentOption(item)}}</p>
            </section>
          </article>
          <p
            v-if="isShowCkjr"
            class="c-pa c-fc-sgray"
            style="font-size:20px;left:50%;bottom:36px;transform:translate(-50%, 0);"
          >{{showCkjrText}}</p>
        </div>
        <div
          class="anvasContent"
          :id="'canvas' + item.promotionNum"
          :key="index"
          v-else-if="item.promotionNum == 4 && curPromotionNum == item.promotionNum"
        >
          <img
            class="c-w100 c-h img-pe-none"
            :src="$addXossFilter(item.isCustomImg == 1 ? item.promotionImg : DEFAULT_BG_LIST[4])"
            alt=""
          >
          <p
            class="c-pa c-ws-n"
            style="font-size:28px;left:50%;top:936px;transform:translate(-50%, 0);"
            :style="'color:'+item.wordColor"
          >{{textContentOption(item)}}</p>
          <p
            class="c-pa c-ws-n"
            style="font-size:28px;left:50%;bottom:120px;transform:translate(-50%, 0);"
            :style="'color:'+item.wordColor"
          >{{text3ContentOption(item)}}</p>
          <img
            class="c-pa c-bg-white"
            style="left:50%;bottom:240px;width:148px;height:148px;transform:translate(-50%, 0);"
            :src="$addXossFilter(mpQrcode)"
            alt=""
          >
          <p
            v-if="isShowCkjr"
            class="c-pa c-fc-sgray"
            style="font-size:20px;left:50%;bottom:12px;transform:translate(-50%, 0);"
          >{{showCkjrText}}</p>
        </div>
        <div
          class="anvasContent"
          :id="'canvas' + item.promotionNum"
          :key="index"
          v-else-if="curPromotionNum == item.promotionNum"
        >
          <img
            class="c-w100 c-h img-pe-none"
            :src="$addXossFilter(item.promotionImg)"
            alt=""
          >
          <template v-for="(childItem, childIndex) in item.content">
            <div
              :style="styleObject(childItem)"
              class="c-pa c-table c-wordBreakAll"
              :key="childIndex"
              v-if="childItem.type == 2"
            >
              <span
                :style="'vertical-align:'+childItem.verticalAlign"
                class="c-tableCell"
              >{{childItem.name}}</span>
            </div>
            <div
              v-if="childItem.type == 4 || childItem.type == 5"
              :key="childIndex"
              :style="styleObject(childItem)"
              class="c-pa c-table c-wordBreakAll"
            >
              <span
                class="c-tableCell"
                :style="'vertical-align:'+childItem.verticalAlign"
              >{{childItem.name}}</span>
            </div>
            <img
              :key="childIndex"
              v-if="childItem.type == 1"
              class="img-pe-none c-pa"
              :style="imgStyleObject(item)"
              :src="$addXossFilter(mpQrcode)"
              alt=""
            >
            <div
              class="c-pa c-table c-wordBreakAll"
              :key="childIndex"
              v-if="childItem.type == 6"
              :style="headStyleObject(childItem)"
            >
              <img class="img-pe-none c-brp50 c-m-0auto" style="width:115px;height:115px;" :src="$addXossFilter(headimgurl, require('@/assets/defult_head.png'))" alt="">
            </div>
          </template>
          <p
            v-if="isShowCkjr"
            class="c-pa c-fc-sgray"
            style="font-size:20px;left:50%;bottom:12px;transform:translate(-50%, 0);"
          >{{showCkjrText}}</p>
        </div>
      </template>
    </div>
    <template v-if="companyAuth && companyAuth.companyNav">
      <nav-bottom-bar :itemIndex="45" v-for="(item,index) in companyAuth.companyNav" :key="index" v-if="item.navType == 45"></nav-bottom-bar>
    </template>
  </div>
</template>

<script>
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import { utilJs } from "@/utils/common.js";
export default {
  name: 'SpeadIndex',
  components: {
    NavBottomBar
  },
  data() {
    return {
      curPromotionNum:0,
      content: [],
      instruction: '',
      isPromotion2PayPage: '',
      liveModuleShowType: '',
      mpQrcode: '',
      netAddress: '',
      nickname: '',
      otherModuleShowType: '',
      promoteData: [],
      defaultTextContent: '',
      defaultText3Content: '',
      radio: 2.5,
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      DEFAULT_BG_LIST: [
        '',
        "https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/spread/1.png",
        "https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/spread/2.png",
        "https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/spread/3.png",
        "https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/spread/4.png",
      ],
      qr: 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/spread/qr.png',
      isShowQr: false,
      headimgurl: '',
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
    import(/* webpackChunkName: "html2canvas" */"@/utils/html2canvas.js").then(res => {
      this.html2canvas = res.default;
    })
  },
  computed: {
    isShowMarginBottom() {
      return this.companyAuth && this.companyAuth.companyNav ? (this.companyAuth.companyNav.find(item => item.navType == 45) ? true : false) : false;
    },
    isShowCkjr() {
      let isShow = this.companyAuth && this.companyAuth.enableShowInfo == 1;
      return isShow;
    },
    showCkjrText() {
      if (!this.companyAuth) {
        return '';
      }
      let returnStr = (this.companyAuth.enableShowInfo == 1 && !this.companyAuth.instruction) ? '创客匠人技术支持' : this.companyAuth.instruction;
      return returnStr;
    },
    promotionImg() {
      return function (item) {
        let promotionImg = '';
        if (item.isCustomImg == 1 || item.isCustom == 1) {
          promotionImg = item.promotionImg
        } else {
          promotionImg = this.DEFAULT_BG_LIST[item.promotionNum];
        }
        return promotionImg;
      }
    },
    // 我是xxx
    textContentOption() {
      return function (item) {
        let textContentOption = '';
        if (item.enableTextContent != 1) {
          textContentOption = this.defaultTextContent;
        } else {
          textContentOption = item.textContent;
        }
        return textContentOption;
      }
    },
    // 我为xxx代言
    text3ContentOption() {
      return function (item) {
        let text3ContentOption = '';
        if (item.enableText3Content != 1) {
          text3ContentOption = this.defaultText3Content;
        } else {
          text3ContentOption = item.text3Content;
        }
        return text3ContentOption;
      }
    },
    styleObject() {
      return function (item) {
        let styleObject = {
          height: item.height * this.radio + 'px',
          width: item.width * this.radio + 'px',
          lineHeight: item.lineHeight * this.radio + 'px',
          left: item.posX * this.radio + 'px',
          top: item.posY * this.radio + 'px',
          fontSize: item.size * this.radio + 'px',
          letterSpacing: item.letterSpacing * this.radio + 'px',
          fontStyle: item.fontStyle,
          fontWeight: item.fontWeight || 'normal',
          color: item.color,
          textAlign: item.textAlign
        };
        return styleObject;
      }
    },
    imgStyleObject() {
      return function (item) {
        let imgStyleObject = {
          width: item.qrcodeW + 'px',
          height: item.qrcodeH + 'px',
          top: item.qrcodeY + 'px',
          left: item.qrcodeX + 'px',
          backgroundColor: item.qrcodeBasicColor == 1 ? '#fff' : ''
        }
        return imgStyleObject;
      }
    },
    headStyleObject() {
      return function (item) {
        console.log(item)
        let headStyleObject = {
          width: item.width * this.radio + 'px',
          height: item.height * this.radio + 'px',
          top: item.posY * this.radio + 'px',
          left: item.posX * this.radio + 'px',
        }
        return headStyleObject;
      }
    }
  },
  methods: {
    getSpreadInfo() {
      utilJs.getMethod(global.apiurl + 'company/promoteShow', res => {
        this.defaultTextContent = `我是${res.nickname}`;
        let companyName = localStorage.getItem("companyName") || '';
        let hideposter = res.promoteData.every(item => item.isShow == 0);
        if (res.promoteData.length <= 0 || hideposter) {
          this.$showCjToast({
            text: "暂无数据",
            type: "warn",
          });
          return;
        }
        //公司名称超过15个字则超过用...显示
        companyName = companyName.length > 15 ? `${companyName.substr(0, 15)}...` : companyName;
        this.defaultText3Content = `我为${companyName}代言`;
        this.instruction = res.instruction;
        this.isPromotion2PayPage = res.isPromotion2PayPage;
        this.liveModuleShowType = res.liveModuleShowType;
        this.mpQrcode = res.mpQrcode;
        this.headimgurl = res.headimgurl;
        this.netAddress = res.netAddress;
        this.nickname = res.nickname;
        this.otherModuleShowType = res.otherModuleShowType;
        this.promoteData = res.promoteData.filter(i => i.isShow == 1);
        console.log(this.promoteData)
        this.curPromotionNum = this.promoteData.length > 0 && this.promoteData[0].promotionNum || 0;
        this.$nextTick(() => {
          this.canvas(this.curPromotionNum)
        })
      })
    },
    canvas(curNum) {
      let domTest = document.getElementById("canvas" + curNum);
      console.log('--domTest--', domTest, curNum)

      if (!domTest) {
        return;
      }
      this.$loading.show({
        text: "推广海报生成中"
      });
      this.html2canvas(domTest, {
        useCORS: true,
        height: domTest.offsetHeight, // 解决当前页面生成图片出现白边问题
        width: domTest.offsetWidth,
      }).then(canvas => {
        let ctx = canvas.getContext("2d");
        this.canvasToImage(ctx);
      })
    },
    canvasToImage(ctx) {
      try {
        // let dataURL = ctx.canvas.toDataURL("image/jpg");
        let dataURL = ctx.canvas.toDataURL("image/png?x-oss-process=style/common");
        document.getElementById("spreadImg").src = '';
        document.getElementById("spreadImg").src = dataURL;
        this.$loading.hide();
      } catch (err) {
        this.$loading.hide();
        console.log(err.message);
        console.log(err.stack);
      }
    },
    clickChangeImg(curNum) {
      if (this.curPromotionNum == curNum) {
        return;
      }
      this.curPromotionNum = curNum;
      this.$nextTick(() => {
        this.canvas(this.curPromotionNum)
      })
    },
    //分享
    wechatShare: function () {
      let title = window.localStorage.getItem("shareTitle");
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/spread/spreadIndex" +
        "?refereeId=" +
        localStorage.getItem("userId");
      let shareDesc = window.localStorage.getItem("shareDesc");
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      var shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/spread/spreadIndex" +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("", "", shareUrl, "");
    }
  },
  activated() {
    setDocumentTitle("分享");
    let $this = this;
    let fromQr = this.$route.query.fromQr;//我要推广他识别二维码跳转到升级会员页面
    if (fromQr == 1) {
      utilJs.getMethod(global.apiurl + 'company/vipType', function (res) {
        let vipType = res.vipType;
        if (vipType == 1) {
          $this.$routerGo($this, "push", { path: "/member/vip/vipUp" });
        } else {
          $this.$routerGo($this, "push", { path: "/" });
        }
      });
      return;
    }
    //如果是ios,则去掉minHeight设置，防止底部前进后退导航挡住页面
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      document.getElementById("spreadRoot").style.minHeight = "";
      document.getElementById("spreadRoot").style.height = "100%";
    }
    this.curPromotionNum = 0;
    this.content = [];
    this.getSpreadInfo();
    this.wechatShare();
  },
  deactivated() {
    this.$loading.hide();
  }
}
</script>

<style lang="less" scoped>
.bg-2F3843 {
  background-color: #2f3843;
}
.check {
  top: calc(50% - 0.4rem);
  left: calc(50% - 0.4rem);
}
.canvasContent {
  width: 6800px;
  height: 1334px;
  top: -999999999px;
  left: -30000000px;
  z-index: -999;
  position: absolute;
  .anvasContent {
    position: relative;
    width: 640px;
    height: 1136px;
  }
}
.mb90 {
  margin-bottom: 2.25rem;
}
</style>